import { Snippet, Tag } from '@/types';

const API_BASE_URL = typeof window === 'undefined' 
  ? 'http://localhost:8080/api/v1' 
  : 'http://localhost:3000/api/v1';

async function fetcher<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, options);
  if (!res.ok) {
    const error = new Error('An error occurred while fetching the data.');
    // Attach extra info to the error object.
    // @ts-ignore
    error.info = await res.json();
    // @ts-ignore
    error.status = res.status;
    throw error;
  }
  const { data } = await res.json();
  return data;
}

export const getSnippets = (page = 1, size = 10, tag?: string): Promise<{ snippets: Snippet[], total: number }> => {
  const params = new URLSearchParams({
    page: String(page),
    size: String(size),
  });
  if (tag) {
    params.append('tag', tag);
  }
  return fetcher(`${API_BASE_URL}/snippets?${params.toString()}`);
};

export const getSnippetById = (id: number): Promise<Snippet> => {
  return fetcher(`${API_BASE_URL}/snippets/${id}`);
};

export const getPopularSnippets = (): Promise<Snippet[]> => {
  return fetcher(`${API_BASE_URL}/snippets/popular`);
};

export const getTags = (): Promise<Tag[]> => {
  return fetcher(`${API_BASE_URL}/tags`);
};

export const createSnippet = (snippet: { title: string; content: string; tags: string[] }): Promise<Snippet> => {
  return fetcher(`${API_BASE_URL}/snippets`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(snippet),
    cache: 'no-store',
  });
};